/*
 * @Author: xiaosihan 
 * @Date: 2022-05-08 14:25:26 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-09-01 16:30:30
 */

import killPort from 'kill-port';
import boxen from 'boxen';
import dotenv from 'dotenv';
// 加载对应环境的env文件
dotenv.config({ path: '.env'});

import cors from "cors";
import express from "express";
import morgan from 'morgan';
import errorHandler from './middleware/error-handler';
import router from './router';
import utils from "./utils";

import dayjs from "dayjs";
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';

dayjs.extend(utc);
dayjs.extend(timezone);

const app = express();

// app.use(cookieParser());
app.use(morgan('dev')); // 打印请求日志
app.use(express.json({ limit: '1024mb' }));
app.use(express.urlencoded({ limit: '1024mb', extended: true }));
app.use(cors()); // 设置跨域

// 添加控制浏览器不缓存本地请求的中间件
app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
    // 设置不缓存的响应头
    res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
    res.setHeader('Pragma', 'no-cache');
    res.setHeader('Expires', '0');
    res.setHeader('Surrogate-Control', 'no-store');
    next();
});

app.use(`/tiny_api`, router);

// 在所有的中间件之后挂载错误处理中间件
app.use(errorHandler())

// 通常会在所有的中间件之后配置处理404内容
// 请求进来从上到下依次匹配
app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
    res.status(404).send('很抱歉，没有找到请求地址');
})

let env = "开发环境";
let port = 82; // 端口
if (utils.isProd) {
    env = "正式环境";
    port = 9000;
}

// 在服务启动前清理端口
killPort(port).then(() => {
    app.listen(port, () =>
        // boxen
        // console.log(env, "服务启动", port, dayjs().tz('Asia/Shanghai').format("YYYY-MM-DD HH:mm:ss"));
        console.log(boxen(`${env},${"服务启动"},${port}, ${dayjs().tz('Asia/Shanghai').format("YYYY-MM-DD HH:mm:ss")}`, {
            padding: 1,
            margin: 1,
            borderColor: 'cyanBright',
            borderStyle: 'round',
            title: '服务启动',
            titleAlignment: 'center',
            textAlignment: 'center',
            dimBorder: true,
        }))
    );
});